package cn.sh.yhk.service.impl;

import cn.sh.yhk.CacheUtils;
import cn.sh.yhk.service.SystemService;
import cn.sh.yhk.vo.CpuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import oshi.hardware.CentralProcessor;

@Component
@Slf4j
public class SystemServiceImpl implements SystemService {
    @Autowired
    CacheUtils cacheUtils;

    /**
     * 获取cpu信息
     *
     * @return cpu信息
     */
    @Override
    public void getCpuInfo() {
        oshi.SystemInfo si = new oshi.SystemInfo();
        CentralProcessor processor = si.getHardware().getProcessor();
        // CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
//        Util.sleep(WAIT_TIME_MS);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softIrq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long ioWait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + ioWait + irq + softIrq + steal;
        CpuInfoVo cpuInfo = new CpuInfoVo();
        cpuInfo.setCpuNum(processor.getLogicalProcessorCount());
        cpuInfo.setTotal((totalCpu));
        cpuInfo.setSys(((double) cSys / totalCpu) * 1000);
        cpuInfo.setUsed(((double) user / totalCpu) * 1000);
        cpuInfo.setWait(ioWait);
        cpuInfo.setFree(((double) idle / totalCpu) * 1000);
        cacheUtils.set("cpuInfo", cpuInfo);
    }
}
